package com.aos.eap.activity;

import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aos.eap.R;
import com.aos.eap.adapter.BadCodeListAdapter;
import com.aos.eap.adapter.MagazineListAdapter;
import com.aos.eap.base.App;
import com.aos.eap.base.BaseDialogActivity;
import com.aos.eap.base.Constant;
import com.aos.eap.bean.DefectBean;
import com.aos.eap.bean.MagazineBean;
import com.aos.eap.bean.WorkEndBean;
import com.aos.eap.bean.net.BaseResponseBean;
import com.aos.eap.utils.MyUtils;
import com.aos.eap.utils.NetUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

import static com.aos.eap.utils.AnimationUtils.arrowAnimation;

public class MFG_WorkEndActivity extends BaseDialogActivity {


    @BindView(R.id.tvUser)
    TextView tvUser;
    @BindView(R.id.etEqpId)
    FreeUI_ClearEditText etEqpId;
    @BindView(R.id.tvLotId)
    TextView tvLotId;
    @BindView(R.id.tvIntoNum)
    TextView tvIntoNum;
    @BindView(R.id.etRemark)
    FreeUI_ClearEditText etRemark;
    @BindView(R.id.ivMagazineArrow)
    ImageView ivMagazineArrow;
    @BindView(R.id.llMagazineTitle)
    LinearLayout llMagazineTitle;
    @BindView(R.id.etMagazineId)
    FreeUI_ClearEditText etMagazineId;
    @BindView(R.id.rvMagazineList)
    RecyclerView rvMagazineList;
    @BindView(R.id.llMagazine)
    LinearLayout llMagazine;
    @BindView(R.id.ivInputArrow)
    ImageView ivInputArrow;
    @BindView(R.id.llInputTitle)
    LinearLayout llInputTitle;
    @BindView(R.id.tvBadCode)
    TextView tvBadCode;
    @BindView(R.id.ivBadCodeArrow)
    ImageView ivBadCodeArrow;
    @BindView(R.id.flBadCode)
    FrameLayout flBadCode;
    @BindView(R.id.etBadNum)
    FreeUI_ClearEditText etBadNum;
    @BindView(R.id.tvAddBadCode)
    TextView tvAddBadCode;
    @BindView(R.id.tvRemoveBadCode)
    TextView tvRemoveBadCode;
    @BindView(R.id.tvBadNumCount)
    TextView tvBadNumCount;
    @BindView(R.id.tvLostNum)
    TextView tvLostNum;
    @BindView(R.id.llInput)
    LinearLayout llInput;
    @BindView(R.id.ivMessageArrow)
    ImageView ivMessageArrow;
    @BindView(R.id.llMessageTitle)
    LinearLayout llMessageTitle;
    @BindView(R.id.rvMessageList)
    RecyclerView rvMessageList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.cbCheckAll)
    CheckBox cbCheckAll;
    @BindView(R.id.tvRemove)
    TextView tvRemove;
    @BindView(R.id.cbCheckAllBadCode)
    CheckBox cbCheckAllBadCode;
    @BindView(R.id.rvBadCodeList)
    RecyclerView rvBadCodeList;

    private MagazineListAdapter magazineListAdapter;
    private BadCodeListAdapter badCodeListAdapter;
    private FreeUI_GeneralPop codePop;
    private WorkEndBean workEndBean;
    private int selectCodePosition = -1;

    @OnClick({R.id.tvAddBadCode, R.id.tvRemoveBadCode, R.id.tvRemove, R.id.flBadCode, R.id.llInputTitle, R.id.llMagazineTitle, R.id.llMessageTitle})
    public void onViewClicked(View view) {
        if (MyUtils.isFastClick()){
            showToast("您点击的太快了",false);
            return;
        }
        switch (view.getId()) {
            case R.id.tvAddBadCode:
                if (selectCodePosition == -1) {
                    showToast("请选择不良代码", false);
                    return;
                }
                String badNum = etBadNum.getText().toString().trim();
                if (FreeApi_StringUtils.isEmpty(badNum)) {
                    showToast("请填写不良数量", false);
                    return;
                }
                int badIntNum = Integer.parseInt(badNum);
                if (badIntNum <= 0) {
                    showToast("请填写正确的不良数量", false);
                    return;
                }
                if (badIntNum > Integer.parseInt(tvLostNum.getText().toString())) {
                    showToast("剩余数量不足", false);
                    return;
                }

                List<DefectBean> data = badCodeListAdapter.getData();
                int i = 0;
                int position = -1;
                for (DefectBean defectBean: data) {
                    if (defectBean.getDefectCode().equals(workEndBean.getDefectList().get(selectCodePosition).getDefectCode())){
                        position = i;
                        break;
                    }

                    i++;
                }

                if (position != -1){
                    showToast("列表已存在",false);
                    etBadNum.setText("");
                    return;
                }else {
                    DefectBean defectBean = new DefectBean();
                    defectBean.setDefectCnt(badNum);
                    defectBean.setDefectCode(workEndBean.getDefectList().get(selectCodePosition).getDefectCode());
                    defectBean.setDefectDesc(workEndBean.getDefectList().get(selectCodePosition).getDefectDesc());
                    badCodeListAdapter.addData(defectBean);
                }

                rvBadCodeList.smoothScrollToPosition(0);
                MyUtils.setEditTextFocus(etBadNum);
                etBadNum.setText("");
                calcNum(badIntNum);
                break;
            case R.id.tvRemoveBadCode:
                int num = 0;
                List<DefectBean> defectBeanList = new ArrayList<>();
                for (DefectBean defectBean1 : badCodeListAdapter.getData()) {
                    if (defectBean1.isSelect()) {
                        defectBeanList.add(defectBean1);
                        num -= Integer.parseInt(defectBean1.getDefectCnt());
                    }
                }
                if (defectBeanList.size() > 0) {
                    badCodeListAdapter.clearPos();
                    badCodeListAdapter.getData().removeAll(defectBeanList);
                    badCodeListAdapter.notifyDataSetChanged();
                    cbCheckAllBadCode.setChecked(false);
                    calcNum(num);
                } else {
                    showToast("未勾选，不能移除", false);
                }
                break;
            case R.id.tvRemove:
                List<MagazineBean> removeList = new ArrayList<>();
                for (MagazineBean magazineBean : magazineListAdapter.getData()) {
                    if (magazineBean.isSelect()) {
                        removeList.add(magazineBean);
                    }
                }
                if (removeList.size() > 0) {
                    magazineListAdapter.clearPos();
                    magazineListAdapter.getData().removeAll(removeList);
                    magazineListAdapter.notifyDataSetChanged();
                    cbCheckAll.setChecked(false);
                } else {
                    showToast("未勾选，不能移除", false);
                }
                break;
            case R.id.flBadCode:
                if (codePop != null) {
                    if (codePop.isShowing()) {
                        codePop.dismiss();
                    } else {
                        FreeApi_PopUtils.setArrowShow(ivBadCodeArrow);
                        codePop.showAsDropDown(flBadCode, 0, 0);
                    }
                }
                break;
            case R.id.llInputTitle:
                if (llInput.getVisibility() == View.VISIBLE) {
                    llInput.setVisibility(View.GONE);
                    arrowAnimation(ivInputArrow, 1);
                } else {
                    llInput.setVisibility(View.VISIBLE);
                    arrowAnimation(ivInputArrow, 2);
                }
                break;
            case R.id.llMagazineTitle:
                if (llMagazine.getVisibility() == View.VISIBLE) {
                    llMagazine.setVisibility(View.GONE);
                    arrowAnimation(ivMagazineArrow, 1);
                } else {
                    llMagazine.setVisibility(View.VISIBLE);
                    arrowAnimation(ivMagazineArrow, 2);
                }
                break;
            case R.id.llMessageTitle:
                if (rvMessageList.getVisibility() == View.VISIBLE) {
                    rvMessageList.setVisibility(View.GONE);
                    arrowAnimation(ivMessageArrow, 1);
                } else {
                    rvMessageList.setVisibility(View.VISIBLE);
                    arrowAnimation(ivMessageArrow, 2);
                }
                break;
        }
    }

    private void calcNum(int badIntNum) {
        int badAllCount = Integer.parseInt(tvBadNumCount.getText().toString());
        int lostCount = Integer.parseInt(tvLostNum.getText().toString());
        tvBadNumCount.setText(String.valueOf(badAllCount + badIntNum));
        tvLostNum.setText(String.valueOf(lostCount - badIntNum));
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_work_end;
    }

    @Override
    protected void initView() {
        tvUser.setText(Constant.CURRENT_USER);
        rvMagazineList.setLayoutManager(new LinearLayoutManager(MFG_WorkEndActivity.this));
        rvMagazineList.setItemAnimator(new DefaultItemAnimator());
        rvMagazineList.addItemDecoration(new DividerItemDecoration(MFG_WorkEndActivity.this, 1));
        cbCheckAll.setOnCheckedChangeListener((compoundButton, isChecked) -> magazineListAdapter.setAll(isChecked));
        magazineListAdapter = new MagazineListAdapter(null);
        magazineListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        magazineListAdapter.isFirstOnly(true);
        rvMagazineList.setAdapter(magazineListAdapter);

        rvBadCodeList.setLayoutManager(new LinearLayoutManager(MFG_WorkEndActivity.this));
        rvBadCodeList.setItemAnimator(new DefaultItemAnimator());
        rvBadCodeList.addItemDecoration(new DividerItemDecoration(MFG_WorkEndActivity.this, 1));
        cbCheckAllBadCode.setOnCheckedChangeListener((compoundButton, isChecked) -> badCodeListAdapter.setAll(isChecked));
        badCodeListAdapter = new BadCodeListAdapter(null);
        badCodeListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        badCodeListAdapter.isFirstOnly(true);
        rvBadCodeList.setAdapter(badCodeListAdapter);

        MyUtils.setEditTextListener(etEqpId, this, this::requestInfoByEqpId);
        MyUtils.setEditTextListener(etMagazineId, this, s -> {
            boolean isHave = false;
            for (MagazineBean entity : magazineListAdapter.getData()) {
                if (entity.getMagazineID().equalsIgnoreCase(s)) {
                    isHave = true;
                    break;
                }
            }
            if (isHave) {
                MyUtils.setEditTextFocus(etMagazineId);
                etMagazineId.setText("");
                showToast("编号已存在列表中", false);
            } else {
                MagazineBean magazineBean = new MagazineBean();
                magazineBean.setMagazineID(s);
                magazineListAdapter.addData(0, magazineBean);
//                rvMagazineList.smoothScrollToPosition(0);
                MyUtils.setEditTextFocus(etMagazineId);
                etMagazineId.setText("");
            }
        });
    }

    private void requestInfoByEqpId(String eqpId) {
        JsonObject map = new JsonObject();
        map.addProperty("EqpID", eqpId);
        NetUtils.requestGetNet(this, "EMS_TrackOutLoad", map, new FreeUI_DialogEntityCallBack<BaseResponseBean<WorkEndBean>>(
                new TypeToken<BaseResponseBean<WorkEndBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<WorkEndBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true,getSupportFragmentManager())) {
                    workEndBean = response.body().getResponse().getBody();
                    setPageData(workEndBean);
                }else {
                    workEndBean = null;
                    setPageData(new WorkEndBean());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<WorkEndBean>> response) {
                super.onError(response);
                uploadLog(response.getException());
                loadError(response.getException(), "EMS_TrackOutLoad");
                workEndBean = null;
                setPageData(new WorkEndBean());
            }
        });
    }


    private void setPageData(WorkEndBean workEndBean) {
        tvLotId.setText(workEndBean.getLotID());
        tvIntoNum.setText(workEndBean.getInputQty());
        magazineListAdapter.setNewData(workEndBean.getMagazineList());
        List<String> list = new ArrayList<>();
        for (DefectBean defectBean : workEndBean.getDefectList()) {
            list.add(defectBean.getDefectCode() + "-" + defectBean.getDefectDesc());
        }

        List<DefectBean> defectVList = workEndBean.getDefectVList();
        badCodeListAdapter.setNewData(defectVList);
        int badNumCount = 0;
        for (DefectBean defectBean : defectVList){
            badNumCount += Double.parseDouble(defectBean.getDefectCnt());
        }
        tvBadNumCount.setText(String.valueOf(badNumCount));
        tvLostNum.setText(String.valueOf(Integer.parseInt(workEndBean.getInputQty()) - badNumCount));
        codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flBadCode.getWidth(), list, ivBadCodeArrow, (s, i) -> {
            String[] split = s.split("-");
            tvBadCode.setText(split[0]);
            selectCodePosition = i;
        });
    }
    @Override
    protected void initData() {

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("结束作业");
        freeUI_titleView.setLeftListener(view -> showBackDialog(MFG_WorkEndActivity.this));
        freeUI_titleView.setRightListener("提交", v -> {
            if (MyUtils.isFastClick()){
                showToast("您点击的太快了",false);
                return;
            }
            if (workEndBean == null) {
                showToast("未获取到页面信息，请重新扫描设备编号", false);
                etEqpId.setText("");
                MyUtils.setEditTextFocus(etEqpId);
                return;
            }
            if (magazineListAdapter.getData().size() == 0) {
                showToast("Magazine列表不能为空", false);
                return;
            }
            JsonObject map = new JsonObject();
            map.addProperty("EqpID", workEndBean.getEqpID());
            map.addProperty("LotID", workEndBean.getLotID());
            map.addProperty("Step", workEndBean.getStep());
            map.addProperty("INPUTQTY", workEndBean.getInputQty());
            map.addProperty("OUTPUTQTY", workEndBean.getOutPutQty());
            map.addProperty("DefectCnt", tvBadNumCount.getText().toString());
            map.add("DefectCodeList", new JsonParser().parse(new Gson().toJson(badCodeListAdapter.getData())).getAsJsonArray());
            map.add("MagazineList", new JsonParser().parse(new Gson().toJson(magazineListAdapter.getData())).getAsJsonArray());
            requestTrackOut(map);
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    private void requestTrackOut(JsonObject map) {
        NetUtils.requestGetNet(this, "EMS_TrackOut", map, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>(
                new TypeToken<BaseResponseBean<?>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<?>> response) {
                if (response.body().isSuccess(getApplicationContext(), false,getSupportFragmentManager())) {
                    FreeApi_DialogUtils.getConfirmDialog(App.app, "确定",
                                    response.body().getResponse().getReturn().getReturnMessage(), new FreeUI_CommonCallback() {
                        @Override
                        public void onSuccess() {
                            MFG_WorkEndActivity.this.finish();
                        }
                    }).show(getSupportFragmentManager(),"success_dialog");
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<?>> response) {
                super.onError(response);
                uploadLog(response.getException());
                loadError(response.getException(), "EMS_TrackOut");
            }
        });
    }
}
